#include "User.hh"
#include "../Exception.hh"

using namespace World;

User::UserMap User::users;

QMutex User::staticLock;

spUser User::construct(QString const& name, QString const& password) {
    QMutexLocker locker(&staticLock);
    UserMap::iterator iter = users.find(name);

    if (iter == users.end()) {
        spUser user(new User(name, password));
        users.insert(name, user);
        return user;
    }

    return *iter;
}

void User::destruct(QString const& name) {
    QMutexLocker locker(&staticLock);

    if (!users.count(name))
        throw UserNotFoundException(name);

    users.remove(name);
}

void User::destruct_all() {
    QMutexLocker sLocker(&staticLock);
    users.clear();
}

spUser User::select(QString const& name) {
    QMutexLocker locker(&staticLock);
    UserMap::iterator iter = users.find(name);

    if (iter == users.end())
        return spUser();

    return *iter;
}

User::User(QString const& name, QString const& password):
    lock(QMutex::Recursive),
    name(name),
//    players(),
    password(password) {}

void User::destruct() {
    User::destruct(name);
}

QString User::get_name() {
    return name;
}

//void User::add_player(spPlayer player) {
//    QMutexLocker locker(&lock);
//    pGalaxy galaxy = player->get_galaxy().data();
//
//    if (players.count(galaxy))
//        throw PlayerExistsException();
//
//    players.insert(galaxy, player);
//}
//
//void User::del_player(spGalaxy galaxy) {
//    QMutexLocker locker(&lock);
//    pGalaxy gal = galaxy.data();
//
//    if (!players.count(gal))
//        throw PlayerNotFoundException();
//
//    players.remove(gal);
//}
//
//void User::del_player(spPlayer player) {
//    del_player(player->get_galaxy());
//}
//
//spPlayer User::get_player(spGalaxy galaxy) {
//    QMutexLocker locker(&lock);
//    PlayerMap::iterator iter = players.find(galaxy.data());
//
//    if (iter == players.end())
//        throw PlayerNotFoundException();
//
//    return *iter;
//}
//
//User::PlayerMap User::get_players() {
//    QMutexLocker locker(&lock);
//    PlayerMap result = players;
//    return result;
//}

void User::set_password(QString const& newPassword) {
    QMutexLocker locker(&lock);
    password = newPassword;
}

